// get的基础自定义
import { HOST } from "./HOST";
import { message } from "antd";
// import vue from 'vue'
import qs from "qs"; // 请求参数处理库
import axios from "axios"; // 请求库
import { ResponseModel } from "../models/common/resPonse";
import { plainToClass } from "class-transformer";
import Cookie from "js-cookie";
export class MyHttp {
  loadingdelay: number = 2500; // 加载效果延迟显示时间
  isShowAjaxChildEff: boolean = true; // 是否显示子项ajax效果
  accesstoken: string | undefined; //token证书
  constructor() {
    axios.defaults.headers.post["Content-Type"] =
      "application/x-www-form-urlencoded"; // 请求头
    axios.defaults.baseURL = HOST; // url公共前缀
    this.setToken();
  }
  setHost(HOST: string) {
    axios.defaults.baseURL = HOST; // url公共前缀
  }
  getHost() {
    return axios.defaults.baseURL; // url公共前缀
  }
  setToken(token?: string) {
    // 设置token证书
    if (token) {
      axios.defaults.headers.Authorization = `Bearer ${this.accesstoken}`;
      this.accesstoken = token;
    } else {
      const accesstoken = Cookie.get("accesstoken") || "";
      if (accesstoken) {
        axios.defaults.headers.Authorization = `Bearer ${this.accesstoken}`;
        this.accesstoken = accesstoken;
      }
    }
  }
  resProcessing<DataClass>(res: ResponseModel<DataClass>) {
    // 自定义业务返回信息判断
    let data = res.data;
    if (res.code === -1) {
      message.error({
        content: res.mes,
        duration: 2000,
      });
    }
  }
  resArryProcessing<DataClass>(resArry: ResponseModel<DataClass>[]) {
    // 自定义业务返回信息数组判断
    let errMes: string | undefined; // 业务异常信息
    resArry.forEach((item, index) => {
      if (item.code === -1) {
        if (index > 0) {
          errMes += "/n";
        }
        errMes += item.mes;
      }
    });
    if (errMes) {
      message.error({
        content: errMes,
        duration: 2000,
      });
    }
  }
  errProcessing(err: any) {
    // 异常处理函数
    console.info("错误", err);
    if (err && err.status === 500) {
      message.error({
        content: "请求失败请检查网络",
        duration: 2000,
      });
    } else {
      message.error({
        content: "请求失败没返回",
        duration: 2000,
      });
    }
  }
  get<DataClass>(
    url: string,
    returnDataClass: new () => DataClass,
    info: object | null | undefined = {},
    host?: string,
    isShowLoading: boolean = true,
    isDisposeRes: boolean = true
  ): Promise<ResponseModel<DataClass>> {
    // get请求

    return new Promise((resolve, reject) => {
      // let delay: NodeJS.Timeout;
      if (isShowLoading && this.isShowAjaxChildEff) {
        // delay = setTimeout(
        message.loading("", 0);
        // ,
        //   this.loadingdelay
        // );
      }
      // get请求
      axios
        .get<ResponseModel<DataClass>>(url, {
          params: info,
          baseURL: host,
          headers: {
            Authorization: `Bearer ${this.accesstoken}`,
          },
        })
        .then((res) => {
          let responseData: ResponseModel<DataClass>; // 服务端返回数据
          if (res.data) {
            let info = res.data;
            responseData = plainToClass(ResponseModel, info, {
              excludeExtraneousValues: true,
            }); // json转DataClass类型对象
            if (info.data) {
              responseData.data = plainToClass(returnDataClass, info.data, {
                excludeExtraneousValues: true,
              }); // json转DataClass类型对象
            } else {
              responseData.data = new returnDataClass();
              console.log(`后台返回${returnDataClass.name}为空`);
            }
          } else {
            // 没数据返回默认数据
            responseData = new ResponseModel();
            responseData.data = new returnDataClass();
            console.log(`后台返回${ResponseModel.name}为空`);
          }

          if (isDisposeRes && this.isShowAjaxChildEff) {
            this.resProcessing(responseData);
          }
          if (isShowLoading && this.isShowAjaxChildEff) {
            // clearTimeout(delay);
            message.destroy();
          }
          resolve(responseData);
        })
        .catch((err) => {
          if (isShowLoading && this.isShowAjaxChildEff) {
            // clearTimeout(delay);
            message.destroy();
          }
          this.errProcessing(err); // 错误处理
          reject(err);
        });
    });
  }
  post<DataClass>(
    url: string,
    returnDataClass: new () => DataClass,
    info: object | null | undefined = {},
    host?: string,
    isShowLoading: boolean = true,
    isDisposeRes: boolean = true
  ): Promise<ResponseModel<DataClass>> {
    // post请求
    return new Promise((resolve, reject) => {
      // let delay: NodeJS.Timeout;
      if (isShowLoading && this.isShowAjaxChildEff) {
        // delay = setTimeout(
        message.loading("", 0);
        // ,this.loadingdelay
        // );
      }

      // get请求
      axios
        .post<ResponseModel<DataClass>>(url, qs.stringify(info), {
          // qs序列化参数 做成stringformdate格式
          headers: {
            // 头部配置
            Accept: "application/json, text/javascript, */*; q=0.01",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            Authorization: `Bearer ${this.accesstoken}`,
          },
          baseURL: host,
          // params: info,
          // paramsSerializer: function(params) {
          //     return Qs.stringify(params, { arrayFormat: 'brackets' })
          // },
        })
        .then((res) => {
          let responseData: ResponseModel<DataClass>; // 服务端返回数据

          if (res.data) {
            let info = res.data;
            responseData = plainToClass(ResponseModel, info, {
              excludeExtraneousValues: true,
            }); // json转DataClass类型对象
            if (info.data) {
              responseData.data = plainToClass(returnDataClass, info.data, {
                excludeExtraneousValues: true,
              }); // json转DataClass类型对象
            }
          } else {
            // 没数据返回默认数据
            responseData = new ResponseModel();
            responseData.data = new returnDataClass();
          }

          if (isDisposeRes && this.isShowAjaxChildEff) {
            this.resProcessing(responseData);
          }
          if (isShowLoading && this.isShowAjaxChildEff) {
            // clearTimeout(delay);
            message.destroy();
          }
          if (isDisposeRes && this.isShowAjaxChildEff) {
            this.resProcessing(responseData);
          }
          if (isShowLoading && this.isShowAjaxChildEff) {
            // clearTimeout(delay);
            message.destroy();
          }
          resolve(responseData);
        })
        .catch((err) => {
          if (isShowLoading && this.isShowAjaxChildEff) {
            // clearTimeout(delay);
            message.destroy();
          }
          this.errProcessing(err);
          reject(err);
        });
    });
  }
  formAjax<DataClass>(
    url: string,
    returnDataClass: new () => DataClass,
    formData: FormData,
    host?: string,
    isShowLoading: boolean = true,
    isDisposeRes: boolean = true
  ): Promise<ResponseModel<DataClass>> {
    return new Promise((resolve, reject) => {
      // let delay: NodeJS.Timeout;
      if (isShowLoading && this.isShowAjaxChildEff) {
        // delay = setTimeout(
        message.loading("", 0);
        // ,this.loadingdelay
        // );
      }

      // get请求
      axios
        .post<ResponseModel<DataClass>>(url, formData, {
          // qs序列化参数 做成stringformdate格式
          headers: {
            // 头部配置
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${this.accesstoken}`,
          },
          baseURL: host,

          // params: info,
          // paramsSerializer: function(params) {
          //     return Qs.stringify(params, { arrayFormat: 'brackets' })
          // },
        })
        .then((res) => {
          let responseData: ResponseModel<DataClass>; // 服务端返回数据

          if (res.data) {
            let info = res.data;
            responseData = plainToClass(ResponseModel, info, {
              excludeExtraneousValues: true,
            }); // json转DataClass类型对象
            if (info.data) {
              responseData.data = plainToClass(returnDataClass, info.data, {
                excludeExtraneousValues: true,
              }); // json转DataClass类型对象
            }
          } else {
            // 没数据返回默认数据
            responseData = new ResponseModel();
            responseData.data = new returnDataClass();
          }

          if (isDisposeRes && this.isShowAjaxChildEff) {
            this.resProcessing(responseData);
          }
          if (isShowLoading && this.isShowAjaxChildEff) {
            // clearTimeout(delay);
            message.destroy();
          }
          if (isDisposeRes && this.isShowAjaxChildEff) {
            this.resProcessing(responseData);
          }
          if (isShowLoading && this.isShowAjaxChildEff) {
            // clearTimeout(delay);
            message.destroy();
          }
          resolve(responseData);
        })
        .catch((err) => {
          if (isShowLoading && this.isShowAjaxChildEff) {
            // clearTimeout(delay);
            message.destroy();
          }
          this.errProcessing(err);
          reject(err);
        });
    });
  }
  getmutidata(promiseArry: Array<Promise<any>>) {
    // let delay: NodeJS.Timeout;
    this.isShowAjaxChildEff = false;
    // delay = setTimeout(
    message.loading("", 0);
    // ,this.loadingdelay
    // );

    Promise.all(promiseArry)
      .then((resArry) => {
        console.log("请求成功返回", resArry);
        // clearTimeout(delay);
      })
      .catch((errArry) => {
        console.log("请求成功返回", errArry);
        // clearTimeout(delay);
      });
  }
}

export default new MyHttp();
